#include "Game.h"

using namespace std;

Game::Game()
{
	//ctor
	m_isEixt = false;
//	m_Player_lst.clear();
}

Game::~Game()
{
	//dtor
//	m_Player_lst.clear();

	// 释放数据库
	m_GameDb.Dispose();
}

// YU_TODO:
void CallTcpServerLoop(TcpServer* _pSock)
{
	_pSock->ConnectLoop();
	//Game::GetInstance().GetSock()->ConnectLoop();
}

void Game::Init()
{
	/// 配置读取
	Config::LoadGlobalConfig("LoginGlobalConfig.txt");

	/// 启用数据库
	string host = Config::globalConfig_map["LoginDBHost"];
	string user = Config::globalConfig_map["LoginDBUser"];
	string pwd = Config::globalConfig_map["LoginDBPwd"];
	string db = Config::globalConfig_map["LoginDB"];

	// 数据库初始化
	m_GameDb.Init(host, user, pwd, db);

	/// 网络启动
	// 服务器部分Test
    string loginIp = Config::globalConfig_map["LoginServerIp"];
    uint16_t loginPort = std::atoi( Config::globalConfig_map["LoginServerPort"].c_str() );
    if(0 == m_ServerSock.Init(loginIp, loginPort)){
		std::thread thread1(CallTcpServerLoop, &m_ServerSock);
		thread1.detach();
    }

	// 各种初始化

	m_GlobalMgr.Init(m_GameDb);
}


void Game::Dispose()
{
	Debug::Log("Game.Dispose");

}


void Game::GameLoop(){
	Debug::State("Start ", __func__);
	int i = 0;

	while(!m_isEixt){

		// 处理ServerSock 发送消息
		if(!m_ServerSock.GetMsgQunue().IsSendEmpty()){
			Message Msg = m_ServerSock.GetMsgQunue().m_MsgSend_que.front();
			m_ServerSock.Send(&Msg);
			m_ServerSock.GetMsgQunue().m_MsgSend_que.pop();
		}

		// 处理ServerSock 接受消息
		if (!m_ServerSock.GetMsgQunue().IsRecvEmpty()){
			Message Msg = m_ServerSock.GetMsgQunue().m_MsgRecv_que.front();
			m_MsgRounter.ServerRounter(&Msg);
			m_ServerSock.GetMsgQunue().m_MsgRecv_que.pop();
		}
	}
}

TcpServer* Game::GetSock()
{
	return &m_ServerSock;
}

// exit
void Game::Exit()
{

	cout<< "Game::Exit()."<< endl;
	m_isEixt = true;
}

void Game::SendMsg2Client(Message* _pMsg){

	_pMsg->Encode();

	// YU_TODO: msg router. to server or to client
	int cmd = (int)_pMsg->m_cmd;
	if(( cmd < MSG_CMD_MIN) && (cmd > MSG_CMD_MAX))
	{
		cout<< "Error. cmd beyond limit."<< endl;
		return;
	}



}
